//
//  MainViewController.swift
//  myBlog
//
//  Created by 姜军君 on 15/10/22.
//  Copyright © 2015年 JJJ. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        /// 添加孩子控制器
        addChildViewControllers()
        
    }
    
    override func viewDidAppear(animated: Bool) {
        
        /// 添加 +
        setupComposeButton()
    }
    
    /// 按钮点击
    func clickComposedButton() {
        
        print(__FUNCTION__)
    }
    
    /// 按钮位置
    private func setupComposeButton() {
    
        let x = view.bounds.width / CGFloat(viewControllers!.count)
        composeButton.frame = CGRectMake(2 * x, 0, x, tabBar.bounds.height)
        
    }
    
    /// 添加所有控制器
    private func addChildViewControllers() {
        
        addChildViewController(HomeTableViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(MessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        addChildViewController(UIViewController())
        addChildViewController(DiscoverTableViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(ProfileTableViewController(), title: "我", imageName: "tabbar_profile")

    }
    
    /// 添加控制器
    private func addChildViewController(vc: UITableViewController, title: String, imageName: String) {
        
        tabBar.tintColor = UIColor.orangeColor()
        
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageName)
        
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
        
    }
    
    /// 懒加载
    private lazy var composeButton: UIButton = {
    
        let btn = UIButton()
        self.tabBar.addSubview(btn)
        
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        btn.addTarget(self, action: "clickComposedButton", forControlEvents: UIControlEvents.TouchUpInside)
        
        return btn;
    }()
}
